package work4.tcp;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServiceClient {
    public static void startClient(){
        try {
            //创建一个服务器端
            ServerSocket serverSocket = new ServerSocket(2021);
            System.out.println("等待连接中...");
            //一直等客户端连接
            Socket socket = serverSocket.accept();
            //建立输入输出流
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            System.out.println("连接成功");
            while (true){
                //从输入流中获取对应信息
                UserMessage message = (UserMessage) objectInputStream.readObject();
                if (null != message){
                    //判断账号密码是否正确
                    if (message.getUser().getAccount().equals("admin") && message.getUser().getPassword().equals("123456")){
                        message.setStatus("success");
                        objectOutputStream.writeObject(message);
                        objectInputStream.close();
                        objectOutputStream.close();
                        return;
                    } else {
                        message.setStatus("fail");
                        objectOutputStream.writeObject(message);
                    }
                } else {
                    message.setStatus("fail");
                    objectOutputStream.writeObject(message);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
